package com.lei.study.cds.unit1;

import org.apache.commons.lang3.StringUtils;
import org.mvel2.MVEL;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 测试不定参数
 * 解决不定参数问题
 *
 * @author 伍磊
 */
public class Test {

    private static final String avg = "def AVG(avgs) {\n" +
            "    count = avgs.length;\n" +
            "    sum = 0;\n" +
            "    for (int i = 0; i < count; i++) {\n" +
            "        sum += avgs[i];\n" +
            "    }\n" +
            "    return sum / count\n" +
            "}\n" +
            "\n";

    private static final Map<String, Object> MAP = new HashMap<>();

    private static final Pattern PATTERN = Pattern.compile("(（(\n|.)*?）)");

    public static void main(String[] args) {
        // 假设函数为avg  参数为avgs
        // 前端传递解析式为 AVG(REV1, REV2, REV3)  ——> 解析式转换为
        String expression = "REV5 + #AVG#(#AVG#(REV1, #MAX#(REV4, REV8, REV9)), REV2, REV3) - (REV6 + REV7)";

        Map<String, String> map = extractMessage(expression);
        System.out.println(map);

        // 模拟数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("REV1", 10);
        dataMap.put("REV2", 11);
        dataMap.put("REV3", 12);
/*
        // 解析
        String compliedExpression = compile(expression, dataMap);

        // init ——> 编译
        Serializable compiled = init(compliedExpression);

        // 执行
        Object o = MVEL.executeExpression(compiled, MAP);
        System.out.println(o);*/
    }

    private static String compile(String expression, Map<String, Object> dataMap) {
        // 1 获取此函数所包含的参数
        Matcher matcher = PATTERN.matcher(expression);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
        return null;
    }

    private static Serializable init(String compliedExpression) {
        // 初始化map数据
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6);
        MAP.put("avgs", integers.toArray());

        // 编译
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(avg).append(compliedExpression);
        return MVEL.compileExpression(stringBuilder.toString());
    }

    public static List<String> extractBracketInnerStr(String str) {
        List<String> result = new ArrayList<>();

        if(!str.contains("(") || !str.contains(")")){
            return result;
        }

        int m = 0, n = 0, count = 0;
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) == '('){
                if(count == 0) {
                    m = i;
                }
                count ++;
            }

            if(str.charAt(i) == ')'){
                count--;
                if (count == 0) {
                    n = i;
                    result.add(str.substring(m+1,n).trim());
                }
            }
        }

        // 检验括号是否配对
        if(count != 0){
            return result;
        }

        // 处理result

        return result;
    }

    private static List<String> parse(String s) {
        Stack st = new Stack();
        String str = "";
        ArrayList<String> array = new ArrayList<>();
        for (char ch : s.toCharArray()) {
            if (ch != ')') {
                st.push(ch);
            } else {
                str = ")";
                while (true) {
                    char tmp = (Character) st.pop();
                    str = tmp + str;
                    if (tmp == '(') {
                        array.add(str);
                        str = "";
                        break;
                    }
                }
            }
        }
        return array;
    }

    /**
     * 提取中括号中内容，忽略中括号中的中括号
     * @param msg
     * @return
     */
    public static Map<String, String> extractMessage(String msg) {
        Map<String, String> map = new HashMap<>();

        // 函数名称
        String[] names = new String[100];

        int start = 0;
        int startFlag = 0;
        int endFlag = 0;
        for (int i = 0; i < msg.length(); i++) {
            if (msg.charAt(i) == '(') {
                startFlag++;
                if (startFlag == endFlag + 1) {
                    start = i;
                }
                // 判断前面是否为代表函数的'#'
                if (msg.charAt(i - 1) == '#') {
                    // 截取到这个函数名称
                    String s = StringUtils.substringAfterLast(msg.substring(0, i - 1), "#");
                    names[startFlag] = s;
                }
            } else if (msg.charAt(i) == ')') {
                endFlag++;
                if (endFlag == startFlag) {
                    if (StringUtils.isNotBlank(names[startFlag])) {
                        map.put(names[startFlag], msg.substring(start + 1, i));
                    }
                }
            }
        }
        return map;
    }


}
